package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareContsant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.PurchaseDetailVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.logging.log4j.spi.ObjectThreadContextMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService detailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceiveList(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PurchaseEntity::getStatus, WareContsant.PurchaseConstant.NEW.getCode())
                .or()
                .eq(PurchaseEntity::getStatus, WareContsant.PurchaseConstant.ASSGINED.getCode());
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void purchaseMerge(PurchaseVo purchaseVo) {
        //如果没指定采购单则创建一个
        Long purchaseId = purchaseVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareContsant.PurchaseConstant.NEW.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //否则使用传来的采购单
        List<Long> items = purchaseVo.getItems();
        List<PurchaseDetailEntity> detailEntities = null;
        if (items != null && items.size() > 0) {
            Long finalPurchaseId = purchaseId;
            detailEntities =
                    items.stream().map(item -> {
                        PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                        detailEntity.setId(item);
                        detailEntity.setPurchaseId(finalPurchaseId);
                        PurchaseDetailEntity detail = detailService.getById(item);
                        if (detail.getStatus() == WareContsant.PurchaseDetailConstant.NEW.getCode()) {
                            detailEntity.setStatus(WareContsant.PurchaseDetailConstant.ASSGINED.getCode());
                        }
                        return detailEntity;
                    }).collect(Collectors.toList());
        }
        detailService.updateBatchById(detailEntities);
    }

    @Transactional
    @Override
    public void receivePurchase(List<Long> purchaseIds) {
        //判断采购单状态是否为已分配
        if (purchaseIds != null && purchaseIds.size() > 0) {
            List<PurchaseEntity> purchaseEntities =
                    purchaseIds.stream().map(purchaseId -> {
                        PurchaseEntity purchase = this.getById(purchaseId);
                        return purchase;
                    }).filter(item -> {
                        if (item.getStatus() == WareContsant.PurchaseConstant.ASSGINED.getCode()) {
                            return true;
                        }
                        return false;
                    }).map(item -> {
                        item.setUpdateTime(new Date());
                        item.setStatus(WareContsant.PurchaseConstant.DOING.getCode());
                        return item;
                    }).collect(Collectors.toList());

            //修改采购单状态
            this.updateBatchById(purchaseEntities);

            //需改采购单关联的采购需求
            purchaseIds.stream().map(item -> {
                List<PurchaseDetailEntity> detailEntities = detailService.queryByPurchaseId(item);
                if (detailEntities != null && detailEntities.size() > 0) {
                    List<PurchaseDetailEntity> detailEntities1 =
                            detailEntities.stream().map(detail -> {
                                detail.setStatus(WareContsant.PurchaseDetailConstant.DOING.getCode());
                                return detail;
                            }).collect(Collectors.toList());
                    detailService.updateBatchById(detailEntities1);
                }
                return item;
            }).collect(Collectors.toList());
        }
    }

    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        Long id = purchaseDoneVo.getId();
        PurchaseEntity entity = this.getById(id);
        if(entity.getStatus()==WareContsant.PurchaseDetailConstant.DOING.getCode()){
            List<PurchaseDetailVo> items = purchaseDoneVo.getItems();
            Boolean flag = true;
            for (PurchaseDetailVo item : items) {
                PurchaseDetailEntity detailEntity = detailService.getById(item.getItemId());
                //2.修改采购需求
                if (item.getStatus() == WareContsant.PurchaseDetailConstant.ERROR.getCode()) {
                    flag = false;//该需求采购失败，不需要修改库存
                    detailEntity.setStatus(item.getStatus());
                    detailService.updateById(detailEntity);
                }
                else{
                    //该需求完成，需要修改库存
                    detailEntity.setStatus(WareContsant.PurchaseDetailConstant.DONE.getCode());
                    detailService.updateById(detailEntity);
                    //3.修改库存
                    wareSkuService.updateByPurchase(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
                }
            }
            //1.修改采购单信息
            PurchaseEntity purchase = this.getById(purchaseDoneVo.getId());
            if(flag==true){
                //采购成功
                purchase.setStatus(WareContsant.PurchaseConstant.DONE.getCode());
                purchase.setUpdateTime(new Date());
            }
            else {
                //采购失败
                purchase.setStatus(WareContsant.PurchaseConstant.ERROR.getCode());
                purchase.setUpdateTime(new Date());
            }
            this.updateById(purchase);
        }

    }

}